public class HeapSort {
    public static void main(String[] args) {
        int[] arr = {6,5,7,3,9,8,5,2};
        heapSort(arr);
        for (int n : arr) {
            System.out.println(n);
        }
    }

    private static void heapSort(int[] arr) {
        createBigHeap(arr);
        int end = arr.length-1;
        for (int i = arr.length - 1; i > 0; i--) {
            int temp = arr[0];
            arr[0] = arr[i];
            arr[i] = temp;
            end--;
            shiftDown(arr, 0, end);
        }
    }

    private static void  createBigHeap(int[] arr) {
        for (int parent = (arr.length-1-1)/2; parent >= 0; parent--) {
            shiftDown(arr, parent, arr.length);
        }
    }

    private static void shiftDown(int[] arr, int parent, int end) {
        int child = 2*parent+1;
        while (child < end) {
            if (child + 1 < arr.length && arr[child] < arr[child+1]) {
                child++;
            }
            if (arr[child] > arr[parent]) {
                int tmp = arr[parent];
                arr[parent] = arr[child];
                arr[child] = tmp;
                parent = child;
                child = 2*parent+1;
            } else {
                break;
            }
        }
    }
}
